package trystero.lib.auth.clientlogin;

import java.util.Vector;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import trystero.lib.http.HTTPClient;
import trystero.lib.http.Cookie;
import trystero.lib.http.HTTPRequestState;
import trystero.lib.http.POSTData;
import trystero.lib.http.hc.HTTPClientImpl;
import trystero.lib.util.StreamUtils;
import trystero.lib.auth.ReaderAuth;

public class ReaderAuthImpl extends ReaderAuth
{
   protected String magic; 

   public ReaderAuthImpl(String username, String password)
   {
      super(username, password);
   }

   public void authenticate(HTTPRequestState state) throws Exception
   {
      state.addHeader("Authorization", "GoogleLogin auth=" + magic());
   }

   protected String magic() throws Exception
   {
      if(magic != null)
	 return magic;

      if(client() == null)
         client(new HTTPClientImpl());

      HTTPRequestState state = new HTTPRequestState();
      state.url("https://www.google.com/accounts/ClientLogin");

      POSTData data = new POSTData();
      data.add("accountType", "GOOGLE");
      data.add("service", "reader");
      data.add("Email", this.username);
      data.add("Passwd", this.password);
      state.data(data);

      this.magic = findMagic(client().post(state));
      return this.magic;
   }


   public static String findMagic(InputStream input)
   {
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      String ret = null;

      while(true)
      {
         String line;
         try
         {
            line = reader.readLine();
         }
         catch(Exception e)
         {
            return null;
         }

         if(line == null)
            return ret;

         if(line.startsWith("Auth="))
 	 {
            String[] parts = line.split("=", 2);
            ret = parts[1];
	    return ret;
 	 }
      }
   }

   public String findMagic(String input)
   {
      String[] lines = input.split("\n");
      for(int i = 0; i < lines.length; i++)
	 if(lines[i].startsWith("Auth="))
         {   
	    String[] parts = lines[i].split("=", 2);
	    return parts[1];
	 }

      return null;
   }
}
